#coding=utf-8
#LightCam PSIS 
#init by hfh 20150923

import multiprocessing,subprocess,sys
import socket,os,time,re,traceback,json,binascii
import lc_libs,pymongo

def gen_client_list():
	clientlist=[]
	try:
		filename="/cffex/trade/biz/psis/log/clientlist.txt"
		#filename="/monitor/LightCam/temp/clientlist.txt"
		for line in open(filename,'rb').readlines():
			lines=line.strip('\r\n').split(',')
			if len(lines)<5 or lines[0]=='memberid':
				continue
			else:
				info={
					'hostname':agent_hostname,
					'memberid':lines[0],
					'operid':lines[1],
					'termtype':lines[2],
					'version':lines[3],
					'time':lines[4]
				}
				clientlist.append(info)
		#print clientlist
		file=open("/monitor/LightCam/temp/clientlist.json",'w')
		file.write(json.dumps(clientlist))
		file.close()
	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()

def gen_bank_link():
	banklink=[]
	try:
		comd="netstat -an|grep 20106|grep ESTABLISHED"
		#comd="cat /monitor/LightCam/temp/banklink.txt"
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		for line in popen.stdout.read().split('\n'):
			if len(line)<6:
				continue
			else:
				info={
					'hostname':agent_hostname,
					'ipaddr':line.split()[4].split(':')[0]
				}
				banklink.append(info)
		#print banklink
		file=open("/monitor/LightCam/temp/banklink.json",'w')
		file.write(json.dumps(banklink))
		file.close()
	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()
		
def gen_member_link():
	memberlink=[]
	try:
		comd="netstat -an|grep 20109|grep ESTABLISHED"
		#comd="cat /monitor/LightCam/temp/memberlink.txt"
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		for line in popen.stdout.read().split('\n'):
			if len(line)<6:
				continue
			else:
				info={
					'hostname':agent_hostname,
					'ipaddr':line.split()[4].split(':')[0]
				}
				memberlink.append(info)
		#print memberlink
		file=open("/monitor/LightCam/temp/memberlink.json",'w')
		file.write(json.dumps(memberlink))
		file.close()
	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()

def gen_portstatus():
	portstatus=[]
	try:
		comd="netstat -an|grep -w 6006|grep ESTABLISHED|wc -l"
		#comd="cat /monitor/LightCam/temp/passcon.txt|grep 6006|grep ESTABLISHED|wc -l"
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		passcon=popen.stdout.read()
		
		comd="netstat -an|grep -w 1521|grep ESTABLISHED|wc -l"
		#comd="cat /monitor/LightCam/temp/dbcon.txt|grep 1521|grep ESTABLISHED|wc -l"
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		dbcon=popen.stdout.read()

		info={
			'hostname':agent_hostname,
			'passcon':passcon.strip('\r\n '),
			'dbcon':dbcon.strip('\r\n ')
		}
		portstatus.append(info)
		
		file=open("/monitor/LightCam/temp/portstatus.json",'w')
		file.write(json.dumps(portstatus))
		file.close()
		
	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()

def gen_processstatus():
	processstatus=[]
	try:
		comd=r'''
			ps -fu trade|awk 'NR>1{$1=$2=$3=$4=$5=$6=$7="";print}'
		'''
		#comd=r'''
		#	cat /monitor/LightCam/temp/process.txt|awk 'NR>1{$1=$2=$3=$4=$5=$6=$7="";print}'
		#'''
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		for line in popen.stdout.read().split('\n'):
			if len(line)<3:
				continue
			info={
				'hostname':agent_hostname,
				'process':line.strip('\r\n ')
			}
			processstatus.append(info)
		#print processstatus
		file=open("/monitor/LightCam/temp/processstatus.json",'w')
		file.write(json.dumps(processstatus))
		file.close()
	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()

if __name__ == "__main__":
	
	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	today=time.strftime('%Y%m%d',time.localtime())
	os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()

	agent_hostname=lc_libs.lc_gethostname()
	
	#初始化数据库
	db=lc_libs.lc_mongodb_operater('127.0.0.1',27017)

	db.connect()
	Conn=db.getConn()
	if Conn==None:
		print "Can not Connect to the MondbDB"
		exit(0)
	
	dbname='lc_psis'
	psisdb=db.useDatabase(dbname)
	
	#银行连接
	tablename='banklink'
	psisdb.drop_collection(tablename)
	banklinktable=db.UseCollection(psisdb,tablename)

	#会员连接
	tablename='memberlink'
	psisdb.drop_collection(tablename)
	memberlinktable=db.UseCollection(psisdb,tablename)
	
	#会员日志
	tablename='clientlist'
	psisdb.drop_collection(tablename)
	clientlisttable=db.UseCollection(psisdb,tablename)

	while True:
		time.sleep(0.1)
		try:
			
			#会员操作员连接统计
			#/cffex/trade/biz/psis/log/clientlist.txt
			if agent_hostname in ('psismb01','psismb02'):
				gen_client_list()

			#银行连接情况统计
			if agent_hostname in ('psisbk01','psisbk02'):
				gen_bank_link()
			
			#会员连接情况统计
			if agent_hostname in ('psismb01','psismb02'):
				gen_member_link()
			
			#加密机与数据库连接状态统计
			gen_portstatus()
				
			#进程状态统计
			gen_processstatus()
				
				
			time.sleep(10)

		except Exception:
			excinfo=traceback.format_exc()
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" \n"+excinfo+"\n")
			logfile.flush()
			time.sleep(10)
